<template>
  <div class="unsplash-container">
    <a-spin :spinning="loading" tip="加载中..." size="large">
      <!-- 固定的搜索区域 -->
      <div class="search-fixed">
        <!-- 搜索和操作区域 -->
        <a-card class="search-card" :bordered="false">
          <a-space>
            <!-- 自定义搜索框 -->
            <div class="custom-search-box">
              <div class="search-input-wrapper">
                <input
                  v-model="searchText"
                  type="text"
                  placeholder="AI搜索图片..."
                  class="search-input"
                  @keyup.enter="handleSearch(searchText)"
                  @input="handleSearchInput"
                />
                <div class="search-icon" @click="handleSearch(searchText)">
                  <SearchOutlined />
                </div>
                <div v-if="searchText" class="clear-icon" @click="clearSearch">
                  <CloseOutlined />
                </div>
              </div>
            </div>
            <a-button :type="isAllSelected ? 'primary' : 'default'" @click="selectAll">
              <template #icon><SelectOutlined /></template>
              {{ isAllSelected ? '取消全选' : '全选本页' }}
            </a-button>
            <a-button
              type="primary"
              :disabled="selectedImages.length === 0"
              @click="handleDownloadAndUpload"
            >
              <template #icon><UploadOutlined /></template>
              下载并上传 ({{ selectedImages.length }})
            </a-button>
            <a-button-group>
              <a-button
                :type="viewMode === 'popular' ? 'primary' : 'default'"
                @click="switchMode('popular')"
              >
                热门图片
              </a-button>
              <a-button
                :type="viewMode === 'random' ? 'primary' : 'default'"
                @click="switchMode('random')"
              >
                随机图片
              </a-button>
            </a-button-group>
            <a-button :loading="refreshing" @click="refreshCurrentPage">
              <template #icon><SyncOutlined /></template>
            </a-button>
          </a-space>
        </a-card>
      </div>

      <!-- 图片内容区域 -->
      <div class="content-area">
        <!-- 图片展示区域 -->
        <a-card class="image-card" :bordered="false">
          <!-- 图片网格 -->
          <div class="image-grid">
            <div v-for="image in images" :key="image.id" class="image-item">
              <div class="image-card">
                <div class="select-overlay" @click.stop="toggleSelect(image)">
                  <a-checkbox :checked="isSelected(image)" />
                </div>
                <div class="image-wrapper" @click="showImageDetails(image)">
                  <img
                    :src="image.url"
                    :alt="image.description || '暂无描述'"
                    class="image"
                    @error="handleImageError"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 分页器 -->
          <div class="pagination-container">
            <a-pagination
              v-model:current="currentPage"
              :total="totalImages"
              :pageSize="pageSize"
              :show-total="(total: number) => `第 ${currentPage} 页`"
              :show-less-items="true"
              :hideOnSinglePage="false"
              :showSizeChanger="false"
              @change="handlePageChange"
            />
          </div>
        </a-card>

        <!-- 图片详情弹窗 -->
        <a-modal
          v-model:open="detailVisible"
          :title="null"
          width="600px"
          :footer="null"
          @cancel="closeImageDetails"
          centered
          class="image-detail-modal"
        >
          <div class="image-detail">
            <!-- 大图展示 -->
            <div class="detail-image">
              <img
                :src="selectedImage?.url"
                :alt="selectedImage?.description || '暂无描述'"
                style="max-height: 400px"
              />
            </div>
            <!-- 图片信息 -->
            <div class="detail-info">
              <h2>{{ selectedImage?.authorName || '未知作者' }}</h2>
              <p class="description">{{ selectedImage?.description || '暂无描述' }}</p>
              <div class="stats">
                <span class="stat-item">
                  <LikeOutlined /> {{ selectedImage?.likes || 0 }} 喜欢
                </span>
                <a-button type="primary" @click="downloadImage"> 下载原图 </a-button>
              </div>
            </div>
          </div>
        </a-modal>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted } from 'vue'
  import { message } from 'ant-design-vue'
  import {
    LikeOutlined,
    SyncOutlined,
    UploadOutlined,
    SelectOutlined,
    SearchOutlined,
    CloseOutlined,
  } from '@ant-design/icons-vue'
  import { useRouter } from 'vue-router'
  import {
    getPopularPhotosUsingGet1,
    getRandomPhotosUsingGet1,
    searchPhotosUsingGet1,
  } from '@/api/unsplashtupianfuwu'
  // 类型定义
  interface UnsplashImage {
    id: string
    url: string
    authorName: string
    description: string | null
    likes: number
  }

  // 添加缓存 key 常量
  const CACHE_KEY = 'unsplash_image_cache'

  // 缓存管理
  const imageCache = new Map<string, UnsplashImage[]>()
  const getCacheKey = (mode: string, page: number, search?: string) =>
    `${mode}-${page}-${search || ''}`

  // 从 localStorage 恢复缓存
  const loadCacheFromStorage = () => {
    const cached = localStorage.getItem(CACHE_KEY)
    if (cached) {
      const parsedCache = JSON.parse(cached)
      Object.entries(parsedCache).forEach(([key, value]) => {
        imageCache.set(key, value as UnsplashImage[])
      })
    }
  }

  // 保存缓存到 localStorage
  const saveCacheToStorage = () => {
    const cacheObj = Object.fromEntries(imageCache.entries())
    localStorage.setItem(CACHE_KEY, JSON.stringify(cacheObj))
  }

  // 状态定义
  const loading = ref(false)
  const refreshing = ref(false)
  const images = ref<UnsplashImage[]>([])
  const currentPage = ref(1)
  const pageSize = ref(30)
  const totalImages = computed(() => (currentPage.value + 1) * pageSize.value)
  const searchText = ref('')
  const viewMode = ref<'popular' | 'random'>('popular')
  const detailVisible = ref(false)
  const selectedImage = ref<UnsplashImage | null>(null)
  const selectedImages = ref<UnsplashImage[]>([])

  const router = useRouter()

  // 搜索防抖
  const searchDebounce = ref<number | null>(null)

  // 简化图片错误处理
  const handleImageError = (e: Event) => {
    const img = e.target as HTMLImageElement
    img.src = '/src/assets/default_image.png'
  }

  // 获取图片列表
  const fetchImages = async (forceRefresh = false) => {
    const cacheKey = getCacheKey(viewMode.value, currentPage.value, searchText.value)

    if (!forceRefresh && imageCache.has(cacheKey)) {
      images.value = imageCache.get(cacheKey) || []
      return
    }

    loading.value = true
    try {
      let res
      if (searchText.value) {
        res = await searchPhotosUsingGet1({
          query: searchText.value,
          page: currentPage.value,
          perPage: pageSize.value,
        })
      } else if (viewMode.value === 'popular') {
        res = await getPopularPhotosUsingGet1({
          page: currentPage.value,
          perPage: pageSize.value,
        })
      } else {
        res = await getRandomPhotosUsingGet1({
          count: pageSize.value,
        })
      }

              if (res.data.code === 200 && res.data.data) {
          let newImages: UnsplashImage[]
          if (searchText.value && 'photos' in res.data.data) {
            // 搜索结果处理，从 data.photos 中获取数据
            const photos = res.data.data.photos || []
            newImages = photos.map(photo => ({
              id: photo.id || '',
              url: photo.urls?.regular || photo.url || '',
              authorName: photo.user?.name || photo.authorName || '未知作者',
              description: photo.description || photo.alt_description || null,
              likes: photo.likes || 0
            }))
          } else {
            // 随机/热门图片处理
            const data = Array.isArray(res.data.data) ? res.data.data : []
            newImages = data.map(item => ({
              id: item.id || '',
              url: item.urls?.regular || item.url || '',
              authorName: item.user?.name || item.authorName || '未知作者',
              description: item.description || item.alt_description || null,
              likes: item.likes || 0
            }))
          }

          images.value = newImages
          imageCache.set(cacheKey, newImages)
          saveCacheToStorage()
        } else {
        message.error(res.data.message || '获取图片失败')
      }
    } catch (error: unknown) {
      console.error('获取图片失败：', error)
      message.error('获取图片失败：' + (error instanceof Error ? error.message : '未知错误'))
    } finally {
      loading.value = false
    }
  }

  // 刷新当前页
  const refreshCurrentPage = async () => {
    refreshing.value = true
    try {
      await fetchImages(true) // 强制刷新，忽略缓存
    } finally {
      refreshing.value = false
    }
  }

  // 搜索处理
  const handleSearch = (value: string) => {
    if (searchDebounce.value) {
      clearTimeout(searchDebounce.value)
    }
    searchDebounce.value = setTimeout(() => {
      searchText.value = value
      currentPage.value = 1
      fetchImages(true)
    }, 500)
  }

  // 搜索输入框处理
  const handleSearchInput = () => {
    if (searchText.value) {
      handleSearch(searchText.value)
    }
  }

  // 清除搜索框
  const clearSearch = () => {
    searchText.value = ''
    currentPage.value = 1
    fetchImages()
  }

  // 切换模式
  const switchMode = (mode: 'popular' | 'random') => {
    viewMode.value = mode
    currentPage.value = 1
    fetchImages()
  }

  // 页码改变
  const handlePageChange = (page: number) => {
    currentPage.value = page
    fetchImages()
  }

  // 显示图片详情
  const showImageDetails = (image: UnsplashImage) => {
    selectedImage.value = image
    detailVisible.value = true
  }

  // 关闭图片详情
  const closeImageDetails = () => {
    detailVisible.value = false
    selectedImage.value = null
  }

  // 下载图片
  const downloadImage = async () => {
    if (!selectedImage.value?.url) return

    try {
      // 开始下载
      const response = await fetch(selectedImage.value.url)
      const blob = await response.blob()

      // 创建下载链接
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url

      // 设置文件名
      const fileName =
        selectedImage.value.description || `unsplash-${selectedImage.value.id}` || 'image'
      link.download = `${fileName}.jpg`

      // 触发下载
      document.body.appendChild(link)
      link.click()

      // 清理
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      message.success('下载成功')
    } catch (error) {
      message.error('下载失败，请稍后重试')
      console.error('Download error:', error)
    }
  }

  // 切换选择状态
  const toggleSelect = (image: UnsplashImage) => {
    const index = selectedImages.value.findIndex(img => img.id === image.id)
    if (index === -1) {
      selectedImages.value.push(image)
    } else {
      selectedImages.value.splice(index, 1)
    }
  }

  // 检查是否被选中
  const isSelected = (image: UnsplashImage) => {
    return selectedImages.value.some(img => img.id === image.id)
  }

  // 下载并上传处理
  const handleDownloadAndUpload = async () => {
    if (selectedImages.value.length === 0) {
      message.warning('请先选择图片')
      return
    }

    try {
      // 存储选中的图片信息到 sessionStorage
      const imageInfos = selectedImages.value.map(image => ({
        id: image.id,
        url: image.url,
        description: image.description || '',
        authorName: image.authorName || '',
        tags: [],
      }))

      sessionStorage.setItem('unsplashPendingImages', JSON.stringify(imageInfos))

      message.success(`已选择 ${selectedImages.value.length} 张图片`)
      router.push('/user/createPicture?from=unsplash&total=' + selectedImages.value.length)
    } catch (error) {
      message.error('处理图片失败，请重试')
      console.error('处理图片失败:', error)
    }
  }

  // 全选功能
  const selectAll = () => {
    // 如果当前页面的图片都已选中，则取消全选
    if (images.value.every(img => isSelected(img))) {
      selectedImages.value = []
    } else {
      // 否则全选当前页面的图片
      selectedImages.value = [...images.value]
    }
  }

  // 检查是否全选
  const isAllSelected = computed(() => {
    return images.value.length > 0 && images.value.every(img => isSelected(img))
  })

  // 初始化
  onMounted(() => {
    loadCacheFromStorage() // 加载缓存
    fetchImages()
  })
</script>

<style scoped>
  .unsplash-container {
    padding: 4px;
    background: var(--theme-background);
    min-height: calc(100vh - 70px);
    position: relative;
    transition: all 0.3s ease;
  }

  /* 固定的搜索区域 */
  .search-fixed {
    position: fixed;
    top: 70px;
    left: 0;
    right: 0;
    z-index: 100;
    background: var(--theme-background);
    padding: 4px 4px 0;
    transition: all 0.3s ease;
  }

  .search-card {
    background: var(--theme-surface);
    border-radius: 8px;
    margin-bottom: 0;
    border: 1px solid var(--theme-border);
    box-shadow: 0 2px 8px var(--theme-shadow);
    transition: all 0.3s ease;
  }

  /* 内容区域 */
  .content-area {
    margin-top: 110px; /* 增加与搜索栏的距离 */
  }

  .image-grid {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 16px;
    padding: 0;
    margin: 0;
    background: transparent;
  }

  .image-item {
    position: relative;
    aspect-ratio: 1;
  }

  /* 优化卡片样式 */
  :deep(.ant-card-body) {
    padding: 16px;
    background: var(--theme-surface);
    border-radius: 8px;
    box-shadow: 0 2px 8px var(--theme-shadow);
    transition: all 0.3s ease;
  }

  .image-card {
    margin-top: -15px; /* 微调卡片与顶部的距离 */
  }

  .image-item img {
    width: 100%;
    height: 200px;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  .image-item:hover img {
    transform: scale(1.05);
  }

  .pagination-container {
    text-align: center;
    margin-top: 24px;
    padding: 16px;
    background: var(--theme-surface);
    border-radius: 8px;
    box-shadow: 0 2px 8px var(--theme-shadow);
    border: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  .image-detail {
    display: flex;
    flex-direction: column;
    gap: 20px;
    max-height: calc(100vh - 200px);
    overflow: auto;
  }

  .detail-image {
    width: 100%;
    max-height: 400px;
    overflow: hidden;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: var(--theme-background);
    transition: all 0.3s ease;
  }

  .detail-image img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    max-height: 400px;
  }

  .image-detail::-webkit-scrollbar {
    width: 6px;
  }

  .image-detail::-webkit-scrollbar-track {
    background: var(--theme-background);
  }

  .image-detail::-webkit-scrollbar-thumb {
    background: var(--theme-border);
    border-radius: 3px;
  }

  .image-detail::-webkit-scrollbar-thumb:hover {
    background: var(--theme-textSecondary);
  }

  :deep(.image-detail-modal .ant-modal-content) {
    padding: 0;
    overflow: hidden;
    border-radius: 12px;
    box-shadow: 0 8px 24px var(--theme-shadow);
    background: var(--theme-surface);
    transition: all 0.3s ease;
  }

  :deep(.image-detail-modal .ant-modal-body) {
    padding: 0;
  }

  .detail-info {
    padding: 20px;
    background: var(--theme-background);
    border-radius: 8px;
    margin: 0 20px 20px;
    border: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  .detail-info h2 {
    margin-bottom: 16px;
    color: var(--theme-text);
    transition: color 0.3s ease;
  }

  .description {
    color: var(--theme-textSecondary);
    margin-bottom: 16px;
    line-height: 1.6;
    transition: color 0.3s ease;
  }

  .stats {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .stat-item {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--theme-textSecondary);
    transition: color 0.3s ease;
  }

  :deep(.ant-modal-content) {
    padding: 0;
    overflow: hidden;
    background: var(--theme-surface);
    transition: all 0.3s ease;
  }

  :deep(.ant-modal-close) {
    color: var(--theme-text);
    transition: color 0.3s ease;
  }

  :deep(.ant-pagination-item-active) {
    background: var(--theme-primary);
    border-color: var(--theme-primary);
  }

  :deep(.ant-pagination-item-active a) {
    color: var(--theme-surface);
  }

  .image-wrapper {
    position: relative;
    width: 100%;
    height: 200px;
    background: var(--theme-background);
    overflow: hidden;
    transition: all 0.3s ease;
  }

  .image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  .image-card {
    cursor: pointer;
    border-radius: 8px;
    overflow: hidden;
    background: var(--theme-surface);
    box-shadow: 0 2px 8px var(--theme-shadow);
    border: 1px solid var(--theme-border);
    transition: all 0.3s ease;
  }

  .image-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px var(--theme-shadow);
    border-color: var(--theme-primary);
  }

  .select-overlay {
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 2;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    padding: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 1px solid var(--theme-border);
  }

  /* 深色主题下的选择覆盖层 */
  [data-theme="dark"] .select-overlay {
    background: rgba(0, 0, 0, 0.8);
    border-color: var(--theme-border);
  }

  /* 深色主题下的选择覆盖层 */
  [data-theme="dark"] .select-overlay:hover {
    background: rgba(0, 0, 0, 0.9);
    border-color: var(--theme-primary);
  }

  /* 浅色主题下的选择覆盖层 */
  [data-theme="light"] .select-overlay:hover {
    background: rgba(255, 255, 255, 1);
    border-color: var(--theme-primary);
    box-shadow: 0 2px 8px var(--theme-shadow);
  }

  .image-item {
    position: relative;
  }

  :deep(.ant-checkbox-wrapper) {
    margin-right: 0;
  }

  .select-button {
    position: absolute;
    top: 8px;
    right: 8px;
    z-index: 2;
  }

  .select-button .ant-btn {
    background: var(--theme-surface);
    border: 1px solid var(--theme-border);
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  .select-button .ant-btn.selected {
    background: var(--theme-primary);
    color: var(--theme-surface);
    border-color: var(--theme-primary);
  }

  /* 自定义搜索框样式 */
  .custom-search-box {
    width: 300px;
  }

  .search-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: var(--theme-surface);
    border: 1px solid var(--theme-border);
    border-radius: 6px;
    transition: all 0.3s ease;
    overflow: hidden;
  }

  .search-input-wrapper:hover {
    border-color: var(--theme-primary);
  }

  .search-input-wrapper:focus-within {
    border-color: var(--theme-primary);
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  .search-input {
    flex: 1;
    height: 40px;
    padding: 8px 40px 8px 12px;
    background: transparent;
    border: none;
    outline: none;
    font-size: 14px;
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  .search-input::placeholder {
    color: var(--theme-textSecondary);
  }

  .search-icon {
    position: absolute;
    right: 40px;
    top: 50%;
    transform: translateY(-50%);
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--theme-textSecondary);
    cursor: pointer;
    transition: all 0.3s ease;
    border-radius: 4px;
  }

  .search-icon:hover {
    color: var(--theme-primary);
    background: var(--theme-background);
  }

  .clear-icon {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--theme-textSecondary);
    cursor: pointer;
    transition: all 0.3s ease;
    border-radius: 50%;
  }

  .clear-icon:hover {
    color: var(--theme-error);
    background: var(--theme-background);
  }

  /* 输入框主题适配 */
  :deep(.ant-input-search .ant-input) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
    transition: all 0.3s ease;
    border-radius: 4px;
    font-size: 14px;
  }

  :deep(.ant-input-search .ant-input:hover) {
    border-color: var(--theme-primary);
  }

  :deep(.ant-input-search .ant-input:focus) {
    border-color: var(--theme-primary);
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }

  :deep(.ant-input-search .ant-input::placeholder) {
    color: var(--theme-textSecondary);
  }

  :deep(.ant-input-search .ant-input-group-addon) {
    display: none;
  }

  /* 按钮主题适配 */
  :deep(.ant-btn) {
    transition: all 0.3s ease;
  }

  :deep(.ant-btn-default) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
  }

  :deep(.ant-btn-default:hover) {
    border-color: var(--theme-primary);
    color: var(--theme-primary);
  }

  :deep(.ant-btn-primary) {
    background: var(--theme-primary);
    border-color: var(--theme-primary);
    color: var(--theme-surface);
  }

  :deep(.ant-btn-primary:hover) {
    background: var(--theme-secondary);
    border-color: var(--theme-secondary);
    color: var(--theme-surface);
  }

  /* 复选框主题适配 */
  :deep(.ant-checkbox) {
    transition: all 0.3s ease;
  }

  :deep(.ant-checkbox .ant-checkbox-inner) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    transition: all 0.3s ease;
  }

  :deep(.ant-checkbox:hover .ant-checkbox-inner) {
    border-color: var(--theme-primary);
  }

  :deep(.ant-checkbox-checked .ant-checkbox-inner) {
    background: var(--theme-primary);
    border-color: var(--theme-primary);
  }

  /* 加载状态主题适配 */
  :deep(.ant-spin) {
    color: var(--theme-primary);
  }

  :deep(.ant-spin-dot-item) {
    background-color: var(--theme-primary);
  }

  /* 分页器主题适配 */
  :deep(.ant-pagination .ant-pagination-item) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  :deep(.ant-pagination .ant-pagination-item:hover) {
    border-color: var(--theme-primary);
    color: var(--theme-primary);
  }

  :deep(.ant-pagination .ant-pagination-item-active) {
    background: var(--theme-primary);
    border-color: var(--theme-primary);
    color: var(--theme-surface);
  }

  :deep(.ant-pagination .ant-pagination-prev),
  :deep(.ant-pagination .ant-pagination-next) {
    background: var(--theme-surface);
    border-color: var(--theme-border);
    color: var(--theme-text);
    transition: all 0.3s ease;
  }

  :deep(.ant-pagination .ant-pagination-prev:hover),
  :deep(.ant-pagination .ant-pagination-next:hover) {
    border-color: var(--theme-primary);
    color: var(--theme-primary);
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .image-grid {
      grid-template-columns: repeat(5, 1fr);
    }
  }

  @media (max-width: 992px) {
    .image-grid {
      grid-template-columns: repeat(4, 1fr);
    }
  }

  @media (max-width: 768px) {
    .image-grid {
      grid-template-columns: repeat(3, 1fr);
    }
    
    .search-fixed {
      padding: 8px;
    }
    
    .search-card {
      margin: 0 8px;
    }
  }

  @media (max-width: 576px) {
    .image-grid {
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;
    }
    
    .image-wrapper {
      height: 150px;
    }
  }
</style>
